package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.cc.Const;
import com.gongpingjialoan.data.CategoryData;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepRecord;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.widget.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/7/18.
 */
public class SellCarDetailActivity extends BaseActivity {

    private LoadingDialog loadingDialog;

    private NetDataJson detailNetDataJson;

    private LayoutInflater mLayoutInflater;

    private String car_id;

    private String from;

    private LinearLayout mLinearLayout, kefu;

    private TextView jcTime, jcAddress;

    private TextView titleTextView, mileTextView, carNameTextView, plat_countTextView, timeTextView, car_statusTextView;

    private ImageView mNetworkImageView;

    private CategoryData mCategoryData;

    private static final int LOGINING_FORSEECAR = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "my_sellRecord_detail";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sellcar_detail);
        EventBus.getDefault().register(this);
        setTitle("卖车记录");
        initView();

    }


    private void initView() {
        mCategoryData = GPJApplication.getInstance().getCategoryData();
        loadingDialog = new LoadingDialog(this);
        mLayoutInflater = LayoutInflater.from(this);
        Intent intent = getIntent();
        car_id = intent.getStringExtra("typevalue");
        from = intent.getStringExtra("type");

        String source = intent.getStringExtra("source");
        String job_id = intent.getStringExtra("job_id");
        if (MyPushIntentService.SELLCARHISTORYDETAIL.equals(from)) {
            StepRecord.recordStep(this, "pushnotification", "{type:" + from + ",typevalue:" + car_id + ",source:" + source + ",job_id:" + job_id + "}");
        }
        mLinearLayout = (LinearLayout) findViewById(R.id.platmain);
        kefu = (LinearLayout) findViewById(R.id.kefu);
        titleTextView = (TextView) findViewById(R.id.title_text);
        carNameTextView = (TextView) findViewById(R.id.carName);
        plat_countTextView = (TextView) findViewById(R.id.plat_count);
        timeTextView = (TextView) findViewById(R.id.time);
        car_statusTextView = (TextView) findViewById(R.id.car_status);
        mNetworkImageView = (ImageView) findViewById(R.id.car_img);
        mileTextView = (TextView) findViewById(R.id.mile);
        jcTime = (TextView) findViewById(R.id.jc_time);
        jcAddress = (TextView) findViewById(R.id.jc_address);
        kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000253500"));
                startActivity(intent);
            }
        });
        getDataFromNet();
    }

    private void getDataFromNet() {
        if (GPJApplication.getInstance().isLogin()) {
            getData();
        } else {
            Intent i = new Intent(this, LoginActivity.class);
            startActivityForResult(i, LOGINING_FORSEECAR);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        loadingDialog.dismiss();
        if ("checklogin".equals(o.toString())) {

            getDataFromNet();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (detailNetDataJson != null) {
            detailNetDataJson.cancelTask();
            detailNetDataJson = null;
        }

        EventBus.getDefault().unregister(this);
    }


    private void getData() {
        if (detailNetDataJson == null) {
            detailNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    findViewById(R.id.main).setVisibility(View.GONE);
                    loadingDialog.dismiss();
                    Toast.makeText(SellCarDetailActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    findViewById(R.id.main).setVisibility(View.VISIBLE);
                    loadingDialog.dismiss();
                    initData(json);
                }
            });
            detailNetDataJson.setUrl(API.sell_detial);
            detailNetDataJson.addParam("car_id", car_id);
            detailNetDataJson.request("get");
            loadingDialog.show();
        }
    }


    private void initData(JSONObject json) {
        try {
            JSONObject data = json.getJSONObject("data");

            String publish_days = data.getString("publish_days");
            String replied_plat_num = data.getString("replied_plat_num");
            String not_replied_plat_num = data.getString("not_replied_plat_num");
            String text = "已发布 " + publish_days + " 天,有 " + replied_plat_num + " 个商家已响应,还有 " +
                    not_replied_plat_num + " 个商家未响应";
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.new_color)), 4, 4 + publish_days.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.new_color)), 9 + publish_days.length(), 9 + publish_days.length() + replied_plat_num.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.new_color)), 20 + publish_days.length() + replied_plat_num.length(), 20 + not_replied_plat_num.length() + publish_days.length() + replied_plat_num.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            titleTextView.setText(style);

            carNameTextView.setText(data.getString("title"));
            timeTextView.setText(data.getString("create_time"));
            mileTextView.setText(data.getString("year") + "年" + data.getString("month") + "月上牌/" + data.getString("mile") + "万公里");
            String filename = mCategoryData.getLogoByModer(data.getString("model_slug"));
            String logo_url =
                    Const.IMG_DOMAIN
                            + GPJApplication.getInstance().getApiUrlFromMeta("brand_model_logo_img")
                            + filename + "?imageView2/0/w/100/h/100";

            ImageLoad.LoadImage(mNetworkImageView, logo_url, R.drawable.car_loading, R.drawable.car_no, SellCarDetailActivity.this);


            JSONArray plats = data.getJSONArray("plat_list");
            String plat_counts = plats.length() + "";
            plat_countTextView.setText(Utils.changeColor(this, "已为您向 " + plat_counts + " 个平台提交", 5, 5 + plat_counts.length(), R.color.new_color));
            car_statusTextView.setText(data.getString("car_status"));

            JSONObject jcJsonObject = data.getJSONObject("validation_appointment");
            if (jcJsonObject.length() >= 2) {
                jcTime.setText(Utils.getSellCarTime(jcJsonObject.getString("begin_time")));
                jcAddress.setText(jcJsonObject.getString("address"));
            }


            mLinearLayout.removeAllViews();
            if (plats.length() <= 1) {
                mLinearLayout.setVisibility(View.GONE);
            } else {
                mLinearLayout.setVisibility(View.VISIBLE);
                int size = plats.length();

                for (int i = 0; i < size; i++) {
                    View view = mLayoutInflater.inflate(R.layout.plat_item, null);
                    TextView text1 = (TextView) view.findViewById(R.id.text1);
                    TextView text2 = (TextView) view.findViewById(R.id.text2);
                    TextView text3 = (TextView) view.findViewById(R.id.text3);
                    text1.setText(plats.getJSONObject(i).getString("update_time"));
                    text2.setText(plats.getJSONObject(i).getString("plat_name"));
                    text3.setText(plats.getJSONObject(i).getString("status_str"));
                    mLinearLayout.addView(view);
                }
            }
            //  jcTime.setText();

        } catch (JSONException e) {
            findViewById(R.id.main).setVisibility(View.GONE);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING_FORSEECAR) {
                getData();
            }
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }


    @Override
    public void onBackPressed() {
        //表示从推送而来
        if (MyPushIntentService.SELLCARHISTORYDETAIL.equals(from)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }


}
